package cn.yunyichina.provider.base.service.impl;

import cn.yunyichina.provider.base.dao.DeptUserRelationDao;
import cn.yunyichina.provider.base.entity.DeptUserRelation;
import cn.yunyichina.provider.base.vo.DeptUserRequest;
import cn.yunyichina.provider.iface.entity.base.DeptUserResponse;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Created by benny on 2017/5/12.
 */
@Service
public class DeptuserServiceImpl {

    private static final Logger logger = LoggerFactory.getLogger(DeptuserServiceImpl.class);

    protected final int MAX_LOG_LENGTH = 2000;

    @Autowired
    private DeptUserRelationDao deptUserRelationDao;

    /**
     * 获取部门与员工关系数据
     * yyt.base.deptUser.list
     * @param data
     * @return
     */
    public ResponseObject listDeptUser(String data) {
        logger.info("获取部门与员工关系数据入参>>listDeptUser: " + data);
        ResponseObject response = new ResponseObject();
        DeptUserRequest deptUserRequest=null;
        DeptUserRelation wheres = new DeptUserRelation() ;
        String orgId=null;
        String orgName=null;

        if(StringUtils.isBlank(data)) {
            response.setResultCodeAndMessage("1201", "input data is empty");
            return response;
        }else {
            deptUserRequest = JsonUtils.parseObject(data, DeptUserRequest.class);
            if(StringUtils.isBlank(deptUserRequest.getRequestType())){
                response.setResultCodeAndMessage("1201","requseType is empty");
                return response;
            }if(!("1".equals(deptUserRequest.getRequestType())||"0".equals(deptUserRequest.getRequestType()))){
                response.setResultCodeAndMessage("1201","requseType is not support");
                return response;
            }else if(StringUtils.isBlank(deptUserRequest.getOrgId())&&"1".equals(deptUserRequest.getRequestType())){
                response.setResultCodeAndMessage("1201","orgID is empty");
                return response;
            } else{
                BeanUtils.copyProperties(deptUserRequest, wheres);
                List<DeptUserRelation> list = deptUserRelationDao.select(wheres);
                int maxLength = JSON.toJSONString(list).length() >= MAX_LOG_LENGTH ? MAX_LOG_LENGTH : JSON.toJSONString(list).length();
                logger.info("获取部门与员工关系数据数据查询结果>> getListResult: " + JSON.toJSONString(list).substring(0, maxLength));
                if ("1".equals(deptUserRequest.getRequestType())){
                    DeptUserResponse deptUserResponse = new DeptUserResponse();
                    if (!CollectionUtils.isEmpty(list)) {
                        Map<String, List<DeptUserResponse.Department.User>> usersMap = new HashMap<>();
                        Map<String, DeptUserResponse.Department> deptsMap = new HashMap<>();
                        for (DeptUserRelation deptUer : list) {
                            orgId = deptUer.getOrgId();
                            orgName = deptUer.getOrgName();
                            if (usersMap.containsKey(deptUer.getDeptId())) {
                                List<DeptUserResponse.Department.User> usersList = usersMap.get(deptUer.getDeptId());
                                DeptUserResponse.Department.User user = new DeptUserResponse.Department.User();
                                user.setUserId(deptUer.getUserId());
                                user.setUserName(deptUer.getUserName());
                                user.setLoginName(deptUer.getLoginName());
                                usersList.add(user);
                            } else {
                                List<DeptUserResponse.Department.User> userList = new ArrayList<>();
                                DeptUserResponse.Department.User user = new DeptUserResponse.Department.User();
                                user.setLoginName(deptUer.getLoginName());
                                user.setUserId(deptUer.getUserId());
                                user.setUserName(deptUer.getUserName());
                                userList.add(user);
                                usersMap.put(deptUer.getDeptId(), userList);
                                DeptUserResponse.Department dept = new DeptUserResponse.Department();
                                dept.setDeptId(deptUer.getDeptId());
                                dept.setDeptName(deptUer.getDeptName());
                                deptsMap.put(deptUer.getDeptId(), dept);
                            }
                        }
                        Iterator iteratorNor = deptsMap.values().iterator();
                        List<DeptUserResponse.Department> deptList = new ArrayList<>();
                        while (iteratorNor.hasNext()) {
                            DeptUserResponse.Department department = (DeptUserResponse.Department) iteratorNor.next();
                            department.setDeptId(department.getDeptId());
                            department.setDeptName(department.getDeptName());
                            List<DeptUserResponse.Department.User> usersList = usersMap.get(department.getDeptId());
                            department.setUsers(usersList);
                            deptList.add(department);
                        }
                        deptUserResponse.setDepartments(deptList);
                        deptUserResponse.setOrgId(orgId);
                        deptUserResponse.setOrgName(orgName);
                        response.setResultObject(deptUserResponse);
                        return response;
                    }
                }else if("0".equals(deptUserRequest.getRequestType())){
                    response.setResultObject(list);
                    return response;
                }
            }
        }
        return response;
    }


    /**
     * 根据条件获取部门与员工关系数据
     * @param data
     * @interfaceName: yyt.base.deptUser.get
     * @return
     */
    public ResponseObject getDeptUser(String data) {
        logger.info("getDeptUser, request data=" + data);
        ResponseObject response = new ResponseObject();
        DeptUserRelation deptUserRelation = JsonUtils.parseObject(data, DeptUserRelation.class);
        deptUserRelation.setEnableFlag((short) 1);
        List<DeptUserRelation> deptUserRelations = deptUserRelationDao.select(deptUserRelation);
        if(deptUserRelations.size() > 0){
            response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE , Response.SUCCESS_MESSAGE , JsonUtils.toJsonString(deptUserRelations));
        }else{
            response.setResultCodeAndMessageAndResult(Response.FAILURE_CODE , "查无结果" , null);
        }
        return response;
    }
}
